## UR Play doesn't have an open API so let's parse their HTML

module Shin
  module Play
    class Urplay
      
      def new
        self
      end
      
      # Programs
      def programs
        # Response
        response = Base.get('http://www.urplay.se/A-O')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil
        
        if @main_noko != nil
          @array = []
          @main_noko.css('section#alphabet > ul > li').map do |p|
            sluge = p.css('a')[0]['href'].strip.gsub("/Produkter/", '')
            p.css('a > span').remove
            titlee = p.css('a').text.strip
            ide = sluge[/^(\d+)/, 1]
            @array << {id: ide.to_i, slug: sluge, title: titlee}
          end
          
          @array.to_hashugar
        else
          raise NotValid, "Nokogiri failed to parse the HTML."
        end
        
      end
      
      # Errors
      class NotValid         < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end